package com.tutorial.demo.goods.service;

import com.tutorial.demo.goods.mapper.TbgoodsMapper;
import com.tutorial.demo.goods.pojo.Tbgoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TbgoodsServiceImpl {
    @Autowired
    private TbgoodsMapper tbgoodsMapper;
    @Autowired
    private TbgoodsServiceImpl2 serviceImpl2;

    //抛出来的异常被catch了，没有触发回滚
    @Transactional(rollbackFor = Exception.class)
    public int insert(){
        Tbgoods tbgoods = new Tbgoods();
        tbgoods.setName("测试一");
        tbgoodsMapper.insert(tbgoods);
        try{
            Tbgoods tbgoods2 = new Tbgoods();
            tbgoods.setName("测试2");
            serviceImpl2.insert(tbgoods2);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 1;
    }

    //两个都有事务，传播机制是默认的，两个组成了一个事务，困扰的点在于有catch，会整体回滚吗
    @Transactional(rollbackFor = Exception.class)
    public int insert1(){
        Tbgoods tbgoods = new Tbgoods();
        tbgoods.setName("测试一");
        tbgoodsMapper.insert(tbgoods);
        try{
            Tbgoods tbgoods2 = new Tbgoods();
            tbgoods.setName("测试二");
            serviceImpl2.insert1(tbgoods2);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 1;
    }

    //serviceImpl2会新建立一个事务，serviceImpl2会回滚，serviceImpl不会回滚
    @Transactional(rollbackFor = Exception.class)
    public int insert2(){
        Tbgoods tbgoods = new Tbgoods();
        tbgoods.setName("测试一");
        tbgoodsMapper.insert(tbgoods);
        try{
            Tbgoods tbgoods2 = new Tbgoods();
            tbgoods.setName("测试二");
            serviceImpl2.insert2(tbgoods2);
        }catch (Exception e){
            e.printStackTrace();
        }
        return 1;
    }



}
